package com.infore.gateway.main.utils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @Discription TODO
 * @Autor lijh
 * @Date 2023/11/12.
 */
public class PathUtils {

    public static boolean matchPath(String regPath, String path){

        if(regPath.charAt(regPath.length()-1) == '*'){
            String subPath = regPath.substring(0,regPath.length()-2);
            return path.indexOf(subPath) == 0;
        }

        if(regPath.charAt(regPath.length()-1) == '/'){
            regPath = regPath.substring(0,regPath.length()-1);
        }

        if(path.charAt(path.length()-1) == '/'){
            path = path.substring(0,path.length()-1);
        }
        String[] names1 = path.split("/");
        String[] names2 = regPath.split("/");

        if(names1.length != names2.length){
            return false;
        }

        Boolean result = true;
        for (int i=0;i<names1.length;i++){
            String str1 = names1[i];
            String str2 = names2[i];
            if(!str1.equals(str2) && (str2.charAt(0) !='{' || str2.charAt(str2.length()-1) !='}')){
                result = false;
                break;
            }

        }

        return result;


    }

    public static boolean matchPathList(List<String> regPathList, String path){
        Boolean result = false;
        if(regPathList == null || regPathList.isEmpty()){
            return result;
        }
        result = Optional.ofNullable(regPathList).orElse(Collections.emptyList()).stream()
                .anyMatch(regPath -> matchPath(regPath,path));
        return result;
    }

    public static void main(String[] args){
        String regPath = "/app/safeRest/address-book/detail/*";
        String path = "/app/safeRest/address-book/detail/123/567";
        boolean b = PathUtils.matchPath(regPath, path);
        System.out.println(b);

    }
}
